﻿using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsApplication2.网络.Base.DNS解析
{
    public partial class Form1 : Form
    {
        [DllImport("Iphlpapi.dll", EntryPoint = "SendARP")]
        public static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);

        [DllImport("Ws2_32.dll")]
        public static extern int inet_addr(string ip);

        public Form1()
        {
            InitializeComponent();
        }

        private static Int64 getRemoteMac(string remoteIp)
        {
            Int32 Idest = inet_addr(remoteIp);

            try
            {
                Int64 macinfo = new long();
                Int32 len = 6;
                int res = SendARP(Idest, 0, ref macinfo, ref len);
                return macinfo;
            }

            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                return 0;
            }
        }

        /// <summary>
        /// jie xi ip
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBoxInput.Text == "")
            {
                MessageBox.Show("null");
                return;
            }

            try
            {
                IPHostEntry iphosts = Dns.Resolve(textBoxInput.Text);
                foreach (IPAddress ip in iphosts.AddressList)
                {
                    long Address = ip.Address;

                    //this.listBoxIPs.Items.Add("ip:"+Address.ToString());
                    this.listBoxIPs.Items.Add("ip:" + ip.ToString());
                }

                //textBoxHostName.Text = iphosts.HostName;

                IPAddress addr = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
                listBoxIPs.Items.Add("本机局域网ip：" + addr);
                   
                Int64 macinfo = getRemoteMac(addr.ToString());
                byte[] temp = new byte[6];
                for (int i = 0; i < 6; i++)
                {
                    temp[i] = Convert.ToByte(macinfo % 256);
                    macinfo /= 256;
                }

                string strResult = string.Format("{0:x}-{1:x}-{2:x}-{3:x}-{4:x}-{5:x}",
                    temp[0], temp[1], temp[2], temp[3], temp[4], temp[5]);

                //this.listBoxIPs.Items.Add("本机mac:" + strResult);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can't Access" + ex.Message, "Exception");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }
}